package com.lagou.edu.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * @author tudedong
 * @description
 * @date 2020-07-05 16:42:28
 */
public class EmailUtils {

    /**
     *
     *
     * @author  caiwei
     * @date    2020-11-26 22:53
     * @param   mailHost    邮箱的服务器地址
     * @param   mailFrom    邮件的发件人
     * @param   passwordMailFrom    授权码
     * @param   mailTo    邮件的收件人
     * @param   mailTitle    邮件的标题
     * @param   mailContent    邮件的文本内容
     * @return  void
     */
    public static void sendEmail(String mailHost, String mailFrom, String passwordMailFrom, String mailTo,
                     String mailTitle, String mailContent) throws MessagingException, GeneralSecurityException {
        Properties properties = new Properties();
        //设置qq邮箱的服务器
        properties.put("mail.smtp.host", mailHost);
        //邮件发送协议
        properties.put("mail.transport.protocol", "smtp");
        //验证用户名以及邮箱授权码
        properties.put("mail.smtp.auth", "true");

        //关于qq邮箱，还要设置SSL加密
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);

        //创建定义整个应用程序所需的环境信息的session
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication( mailFrom,passwordMailFrom);
            }
        });
        //开启session的调试模式，可以查看当前邮件发送状态
        session.setDebug(true);
        //通过session得到transport对象
        Transport transport = session.getTransport();
        //使用邮箱的用户名和授权码连上邮箱服务器
        transport.connect(mailHost,mailFrom,passwordMailFrom);
        //创建邮件
        MimeMessage mimeMessage = new MimeMessage(session);
        //指明邮件的发件人
        mimeMessage.setFrom(new InternetAddress(mailFrom));
        //指明邮件的收件人
        mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress( mailTo));
        //邮件的标题
        mimeMessage.setSubject(mailTitle);
        //邮件的文本内容
        mimeMessage.setContent(mailContent,"text/html;charset=utf-8");
        //发送邮件
        transport.sendMessage(mimeMessage,mimeMessage.getAllRecipients());
        //关闭连接
        transport.close();
    }

    public static void main(String[] args) throws GeneralSecurityException, MessagingException {
        sendEmail("smtp.qq.com","562908495@qq.com",
                "htzhgoivxynsbcja","562908495@qq.com",
                "注册验证码","您好，本次登录的验证码为：546289，将在10分钟之后过期");
    }
}
